package o2o.web.actions.divide;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.ShopAgentRelationMemory;
import o2o.cache.divide.CityAgentFeeMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.divide.CityAgentFeeInfo;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.agent.CityAgentVO;
import o2o.dao.VO.divide.CityAgentFeeVO;
import o2o.web.actions.agent.CityAgentMan;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @User: @Created by yangtk
 * @Date: @Date 2019/9/28 9:36
 * @Classname: CityAgentFeeAction
 * @To change this template use File | Settings | File Templates.
 */
@RestController
public class CityAgentFeeAction {


    // 1. 添加当前上商圈的
    @RequestMapping(method = RequestMethod.POST, value = "admin/city/agent/fee/add")
    public Object city_agent_add(String token,
                                 @RequestParam(defaultValue = CityAgentFeeInfo.DELIVERY_TYPE_AGENT) String type,               // 类型  按城市  还是商圈
                                 Long agentId,             // -1 标识默认的商圈
                                 @RequestParam(defaultValue = "0") Integer isDefault,            // 1 默认 0 非默认 非默认的话必须有时间段
                                 String timeContent,       // 时间段  例如 10:00-11:00
                                 Double fixedCost,         // 指定距离以内的配送费
                                 Double withinDistance,    // 距离:配送指定距离以内 只收取固定费用
                                 Double oneKmCost,         // 单公里费用:超出指定距离单公里费用
                                 Double secondaryPsMoney) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        CityAgentFeeInfo info = new CityAgentFeeInfo();
        if (!CityAgentFeeInfo.DELIVERY_TYPE_AGENT.equals(type)) {
            return AjaxResult.errorResult("未知的类型");
        }
        if (CityAgentFeeInfo.DELIVERY_TYPE_AGENT.equals(type) && agentId == null) {
            return AjaxResult.errorResult("请选择商圈");
        }
        info.setType(type).setAgentId(agentId);
        if (agentId != CityAgentFeeInfo.DELIVERY_DEFAULT_AGENT) {
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
            if (cityAgent == null) {
                return AjaxResult.errorResult("商圈信息不能为空");
            }
        }
        if (withinDistance == null || withinDistance < 0
                || fixedCost == null || fixedCost < 0
                || oneKmCost == null || oneKmCost < 0) {
            return AjaxResult.errorResult("配送费设置不正确");
        }
        info.setWithinDistance(withinDistance).setFixedCost(fixedCost).setOneKmCost(oneKmCost);
//        boolean isHasDefault = CityAgentFeeMemory.getInstance().isExitDefaultCityAgentFee(agentId);
//        if (isDefault == 0 && StringUtils.isEmpty(timeContent)) {
//            return AjaxResult.errorResult("时间区间不能为空");
//        } else {
//            if (!isHasDefault) {
//                return AjaxResult.errorResult("请首先设置默认费用设置");
//            }
//            info.setTimeContent(timeContent);
//        }
//        if (isHasDefault && isDefault == 1) {
//            return AjaxResult.errorResult("一个商圈仅能设置一个默认的配送费设置");
//        }
        if (StringUtils.isEmpty(timeContent)) {
            return AjaxResult.errorResult("时间区间不能为空");
        }
        info.setTimeContent(timeContent);
        if (secondaryPsMoney != null && secondaryPsMoney >= 0) {
            info.setSecondaryPsMoney(secondaryPsMoney);
        }
        Long cTime = DateUtils.getCurrTime();
        info.setCreateTime(cTime).setCreateUser(user.getUsername());
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.CITY_AGENT_FEE, info);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("添加失败,请稍后重试");
        }
        // 缓存
        CityAgentFeeMemory.getInstance().add(cTime);
        // 数据通讯
        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.CITY_AGENT_FEE_INFO_ADD).setLong01(cTime);
        JmsSender.setTopicSender(notify);

        return AjaxResult.successResult();
    }

    // 5. 打开或者关闭
    @RequestMapping(method = RequestMethod.POST, value = "admin/city/agent/fee/open-close")
    public Object city_agent_open_close(String token, @RequestParam(defaultValue = "1") Integer isOpen, Long id) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (id == null) {
            return AjaxResult.errorResult("id不能为空");
        }
        CityAgentFeeInfo feeInfo = CityAgentFeeMemory.getInstance().get(id);
        if (feeInfo == null) {
            return AjaxResult.errorResult("未获取到信息,请核实");
        }
        if (feeInfo.getIsOpen() == isOpen) {
            return AjaxResult.successResult();
        }
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(PojoTables.CITY_AGENT_FEE)
                .append(" set updateUser = '").append(user.getUsername())
                .append("',isOpen =").append(isOpen).append(" where delFlag = 0 and id =").append(id);
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败,请稍后重试");
        }
        // cache
        CityAgentFeeMemory.getInstance().modify(id);
        return AjaxResult.successResult();
    }


    // 修改
    @RequestMapping(method = RequestMethod.POST, value = "admin/city/agent/fee/modify")
    public Object city_agent_fee_modify(String token, CityAgentFeeInfo info) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (info == null) {
            return AjaxResult.errorResult("信息不能为空");
        }
        if (info.getId() == null) {
            return AjaxResult.errorResult("id不能为空");
        }
        CityAgentFeeInfo feeInfo = CityAgentFeeMemory.getInstance().get(info.getId());

        if (feeInfo == null) {
            return AjaxResult.errorResult("未获取到信息,请核实");
        }
//        if (feeInfo.getIsDefault() == 0 && StringUtils.isEmpty(feeInfo.getTimeContent())) {
//            return AjaxResult.errorResult("时间区间不能为空");
//        }
        if (StringUtils.isEmpty(feeInfo.getTimeContent())) {
            return AjaxResult.errorResult("时间区间不能为空");
        }
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(PojoTables.CITY_AGENT_FEE)
                .append(" set updateUser = '").append(user.getUsername())
                .append("'");
        if (info.getFixedCost() != null && info.getFixedCost() >= 0) {
            sql.append(",fixedCost =").append(info.getFixedCost());
        }
        if (info.getWithinDistance() != null && info.getWithinDistance() >= 0) {
            sql.append(",withinDistance =").append(info.getWithinDistance());
        }
        if (info.getOneKmCost() != null && info.getOneKmCost() >= 0) {
            sql.append(",oneKmCost =").append(info.getOneKmCost());
        }
        if (info.getSecondaryPsMoney() != null && info.getSecondaryPsMoney() >= 0) {
            sql.append(",secondaryPsMoney =").append(info.getSecondaryPsMoney());
        }
//        if (feeInfo.getIsDefault() == 0) {
        sql.append(",timeContent =").append(info.getTimeContent());
//        }
        sql.append(" where delFlag = 0 and id =").append(info.getId());
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败,请稍后重试");
        }
        // cache
        CityAgentFeeMemory.getInstance().modify(info.getId());
        // 数据通讯
        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.CITY_AGENT_FEE_INFO_UPDATE).setLong01(info.getId());
        JmsSender.setTopicSender(notify);
        return AjaxResult.successResult();
    }

    // 3. 删除
    @RequestMapping(method = RequestMethod.POST, value = "admin/city/agent/fee/del")
    public Object city_agent_fee_del(String token, Long id) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (id == null) {
            return AjaxResult.errorResult("id不能为空");
        }
        CityAgentFeeInfo info = CityAgentFeeMemory.getInstance().get(id);
        if (info == null) {
            return AjaxResult.errorResult("未查询到信息");
        }
//        if (info.getIsDefault() == 1) {
//            return AjaxResult.errorResult("不能删除默认的费用设置");
//        }
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(PojoTables.CITY_AGENT_FEE)
                .append(" set delFlag = 1 ,updateUser ='").append(user.getUsername()).append("'")
                .append(" where delFlag = 0 and id =").append(id);
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败,请稍后重试");
        }
        // cache
        CityAgentFeeMemory.getInstance().del(id);
        // 数据通讯
        JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.CITY_AGENT_FEE_INFO_DELETE).setLong01(id);
        JmsSender.setTopicSender(notify);
        return AjaxResult.successResult();
    }

    // 4. 获取列表
    @RequestMapping(method = RequestMethod.POST, value = "admin/city/agent/fee/list")
    public Object admin_city_agent_fee_list(String token, Long agentId) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (agentId == null) {
            return AjaxResult.errorResult("agentId不能为空");
        }
        List<CityAgentFeeVO> vos = CityAgentFeeMan.listOfAgentIdVO(agentId);
        if (vos != null && !vos.isEmpty()) {
            return AjaxResult.successResult(vos.size(), vos);
        }
        return AjaxResult.successResult(0, null);
    }

    // ---------------------------- 手机端获取的---------------------
    @RequestMapping(method = RequestMethod.POST, value = "mobile/city/agent/fee/list")
    public Object admin_city_agent_fee_list(Long agentId, Long shopId, String city, Double lng, Double lat) {
        if (agentId == null) {

        } else if (ValidateUtil.isID(shopId)) {
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
            if (shopInfo == null) {
                return AjaxResult.errorResult("未获取到店铺信息");
            }
            agentId = ShopAgentRelationMemory.getInstance().getAgentByShopId(shopId);
        } else {
            List<CityAgentVO> agentList = CityAgentMan.getCityAgentList(city, lat, lng);
            if (agentList != null && !agentList.isEmpty()) {
                agentId = agentList.get(0).getId();
            }
        }
        List<CityAgentFeeVO> feeVOS = CityAgentFeeMan.mobileListOfCityAgentId(agentId);
        if (feeVOS != null && !feeVOS.isEmpty()) {
            return AjaxResult.successResult(feeVOS.size(), feeVOS);
        }
        return AjaxResult.successResult(0, null);
    }


}
